package com.nbot.server.workers.impl;


import com.nbot.common.command.s2b.ImportantExecuteConfirm;
import com.nbot.server.BotServer;
import com.nbot.server.domain.*;
import com.nbot.server.properties.NbotProperties;
import com.nbot.server.service.*;
import com.nbot.server.workers.DbWorker;
import org.jinterop.dcom.common.JIException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.AsyncResult;

import java.io.UnsupportedEncodingException;
import java.net.UnknownHostException;
import java.util.*;
import java.util.concurrent.Future;

/**
 * server本地数据库处理类
 */
public class DbWorkerImpl implements DbWorker {
    private Logger logger = LoggerFactory.getLogger(this.getClass());

    private static final String SEARCH_KEY = "searchDesc";

    @Autowired
    private PointService pointService;

    @Autowired
    private ImportantexecuteService importantexecuteService;

    @Autowired
    private ChecklogService checklogService;

    @Autowired
    private ChecklogProService checklogProService;

    @Autowired
    private NbotProperties nbotProperties;

    @Autowired
    private AlarmpointService alarmpointService;

    @Autowired
    private AnalogalarmService analogalarmService;

    @Autowired
    private RelevancealarmService relevancealarmService;

    @Override
    public void save() {

//TODO 需要实现

    }

    @Override
    public void saveIEC(ImportantexecuteDO Data) {//重点督办 add wyzc
        importantexecuteService.save(Data);
    }

    @Override
    public ImportantexecuteDO selectIECByKey(Long key) {//重点督办 add wyzc
        return importantexecuteService.get(key);
    }

    @Override
    public void updateIECByKey(ImportantexecuteDO Date) {//重点督办 add wyzc
        importantexecuteService.update(Date);
    }

    @Override
    public void checkIEC() throws JIException, UnknownHostException {//重点督办 add wyzc

        String broadcastflag = "ing";//正在重点督办的标志

        if (importantexecuteService.selectByMoreInfo(broadcastflag) == null) {//无正在播报
            List<ImportantexecuteDO> IECList = importantexecuteService.selectConfirmInfoIsNull();
            if (!IECList.isEmpty())  {//非空
                Date timenow = Calendar.getInstance().getTime();
                for (ImportantexecuteDO target : IECList) {
                    Date plantime = target.getPlantime();
                    int delaytime = Integer.parseInt(target.getDelayinterval()) * 60 * Integer.parseInt(target.getDelaytimes());
                    long actualinterval = (timenow.getTime() - plantime.getTime()) / 1000 - delaytime;//真实间隔秒数-延时时间秒数
                    if (actualinterval > 0) {//超过计划时间  播报 置标志位
                        ImportantExecuteConfirm confirminfo = new ImportantExecuteConfirm(target.getAutoid(), target.getEvent());
                        try {
                            BotServer.addUartMsg(confirminfo);
                        } catch (UnsupportedEncodingException e) {
                            e.printStackTrace();
                        }
//                        BotServer.putCommand(confirminfo);

                        target.setMoreinfo(broadcastflag);
                        importantexecuteService.update(target);
                    }
                }
            }
        }
    }

    @Override
    public void checkLogTrans() throws JIException, UnknownHostException {
        long currentCount = checklogProService.getMaxAutoId();
        long logCount = checklogService.getMaxAutoId();
        if (logCount > currentCount){
            Map<String, Object> params = new HashMap<>();
//            params.put("sort", "autoId");
//            params.put("order", "desc");
            params.put("offset", 0);
            params.put("limit", logCount-currentCount);
            List<ChecklogDO> logData = checklogService.list(params);
            for (int i = logData.size();i > 0;i--){
                ChecklogDO ld = logData.get(i-1);
                ChecklogProDO lpd = new ChecklogProDO();
                lpd.setCheckatid(ld.getAutoid());
                lpd.setPointatid(ld.getAutoid());
                lpd.setTag(ld.getTag());
                lpd.setCheckvalue(ld.getCheckvalue());
                lpd.setChecktimestamp(ld.getChecktimestamp());
                lpd.setAlarmlevel(ld.getAlarmlevel());
                lpd.setDispdesc(ld.getDispdesc());
                lpd.setSearchdesc(ld.getTruthvalue());

                if (ld.getBackup() != null && !ld.getBackup().equals("")) {
                    Map<String, Object> tag = new HashMap<>();
                    tag.put("getdatapath", ld.getTag());
                    switch (ld.getBackup()) {
                        case "KG":
                            List<AlarmpointDO> kg3 = alarmpointService.list(tag);
                            if (kg3.size() == 1) {
                                lpd.setWeizhi(kg3.get(0).getDevice());
                                lpd.setZhanhao(kg3.get(0).getStationid());
                                lpd.setAlarmclass(kg3.get(0).getAlarmclass());
                            } else {
                                logger.info(String.valueOf(kg3.size()));
                            }
                            break;
                        case "MN":
                            List<AnalogalarmDO> mn3 = analogalarmService.list(tag);
                            if (mn3.size() == 1) {
                                lpd.setWeizhi(mn3.get(0).getDirectpointail());
                                lpd.setZhanhao(mn3.get(0).getDirectpoint());
                                lpd.setAlarmclass(mn3.get(0).getAlarmclass());
                            } else {
                                logger.info(String.valueOf(mn3.size()));
                            }
                            break;
                        case "LD":
                            List<RelevancealarmDO> ld3 = relevancealarmService.list(tag);
                            if (ld3.size() > 0) {
                                lpd.setWeizhi(ld3.get(0).getDevice());
                                lpd.setZhanhao(ld3.get(0).getStationid());
                                lpd.setAlarmclass(ld3.get(0).getAlarmclass());
                            } else {
                                logger.info(String.valueOf(ld3.size()));
                            }
                            break;
                        case "TX":
                            lpd.setAlarmclass("监控类");
                            break;
                    }
                }
                checklogProService.save(lpd);
            }
        }
    }

    @Override
    public void read(String key) {
        //TODO 需要实现
    }

    @Override
    public String getTagFormDesc(String descString) {
        Point p = null;

        // p = pointService.selectOne(Condition.create().eq(SEARCH_KEY, descString));
        p = pointService.getTagFormDesc(descString);
        if (p != null) {
            return p.getTag();
        } else {
            return null;
        }

    }

    @Override  //查询精确匹配
    public Point getTagFormSearchdesc(String searchdesc) {
        Point p = null;

        p = pointService.getTagFormDesc(searchdesc);
        return p;
    }

    @Override
    public List<Point> getSaveWeizhiPoint(String weiZhi) {
        //根据开关量进行控制（临时处理）
        if (nbotProperties.isOpcRelatedSearch()) {
            return pointService.getSaveWeizhiPoint(weiZhi);

        } else {
            return null;
        }
    }

    @Override  //查询模糊匹配
    public Point getPointFormDesc(String descString) {
        List<Point> p = null;

        //p = pointService.selectList(Condition.create().like(SEARCH_KEY, descString, SqlLike.DEFAULT));
        p = pointService.getPointFormDesc(descString);
        if (p == null) {
            return null;
        }
        if (p.isEmpty()) {
            return null;
        }
        if (p.size() != 1) {
            return pointService.getTagFormDesc(descString);
        }
        return p.get(0);
    }

    @Override
    public Future<String> getTagFormDescAsync(String descString) {

        Point p = null;

        // p = pointService.selectOne(Condition.create().eq(SEARCH_KEY, descString));
        p = pointService.getTagFormDesc(descString);
        Future<String> future = null;
        if (p != null) {
            future = new AsyncResult<String>(p.getTag());

        }

        return future;

    }
}
